package cash.cmp.personal_financial_system.bigdata;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Component
public class ScheduledTasks {

    ExecuteJob executeJob = new ExecuteJob();
    //每天两点触发运行
    @Scheduled(cron = "0 0 2 * * ?", zone = "Asia/Shanghai")
    public void reportCurrentTime(){
        Date now = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dt = dateFormat.format(now);
        //如果是月初执行bill1
        if(isFirstDayOfMonth(now)){
            executeJob.executeFlow("782f8e0f-938f-4d1d-a22d-79544bcfd413","bill1","bill",dt);
        }
        //如果是月末，先执行bill2，再执行bill3
        else if(isLastDayOfMonth(now)){
            executeJob.executeFlow("782f8e0f-938f-4d1d-a22d-79544bcfd413","bill2","bill",dt);
            executeJob.executeFlow("782f8e0f-938f-4d1d-a22d-79544bcfd413","bill3","bill",dt);
        }
        else{
            executeJob.executeFlow("782f8e0f-938f-4d1d-a22d-79544bcfd413","bill2","bill",dt);
        }
    }
    //判断是否是月末
    public static boolean isLastDayOfMonth(Date date) {
        //1、创建日历类
        Calendar calendar = Calendar.getInstance();
        //2、设置当前传递的时间，不设就是当前系统日期
        calendar.setTime(date);
        //3、data的日期是N，那么N+1【假设当月是30天，30+1=31，如果当月只有30天，那么最终结果为1，也就是下月的1号】
        calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) + 1));
        //4、判断是否是当月最后一天【1==1那么就表明当天是当月的最后一天返回true】
        if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {
            return true;
        }else{
            return false;
        }
    }

    //判断是否是月初
    public boolean isFirstDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
        return calendar.get(Calendar.DAY_OF_MONTH) == 2;
    }
}

